package org.dxy.trigger.listener.workorder;

import com.google.common.eventbus.Subscribe;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.domain.event.workorder.WorkOrderCreatedEvent;
import org.dxy.infrastructure.entity.query.WorkOrderViewEntity;
import org.dxy.infrastructure.persistent.service.WorkOrderViewService;
import org.dxy.trigger.listener.EventListener;
import org.springframework.stereotype.Component;

/**
 * @description: 监听工单创建事件，并更新工单读模型
 * 工单创建后，更新工单基础视图，用于查询和展示
 * @author: dxy
 * @createTime: 2025/8/4 22:15
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class WorkOrderCreatedEventListener implements EventListener<WorkOrderCreatedEvent> {

    private final WorkOrderViewService workOrderViewService;

    /**
     * 处理工单创建事件
     * @param event 工单创建事件，包含工单ID、编码、产品型号等信息
     */
    @Override
    @Subscribe
    public void onEvent(WorkOrderCreatedEvent event) {
        log.info("接收到工单创建事件, event：{}", event.toString());
        
        WorkOrderViewEntity workOrderViewEntity = new WorkOrderViewEntity();
        workOrderViewEntity.setId(event.workOrderId())
                .setWorkOrderCode(event.workOrderCode())
                .setProductModel(event.productModel())
                .setStatus(event.workOrderStatus());
        
        boolean updated = workOrderViewService.updateById(workOrderViewEntity);
        if (updated) {
            log.info("工单读模型更新成功，工单ID={}", event.workOrderId());
        } else {
            log.warn("工单读模型更新失败，工单ID={}", event.workOrderId());
        }
    }
}
